const express = require('express');
let router = express.Router();
const subModel = require("./../model/subModel");
const subUserModel = require("./../model/subUserModel")
const {v4: uuidv4} = require("uuid");


router.post('/list',async function(req,res,next){
   const page = parseInt(req.body.page,10)
   const pageSize = parseInt(req.body.pageSize,10)
   let {uid,phoneNum,email,subType,bqMoney,subNum,startDate,endDate} = req.body
    // 参数合理性检查
    if(isNaN(page) || isNaN(pageSize) || page < 1 || pageSize < 1){
        return res.status(400).send({
            code: 400,
            message: '查询参数不正确'
        });
    }
    // 计算分页跳过的文档数量
    const skipValue = (page - 1) * pageSize;
    // 构建查询条件
    let query = {};
    // if (username) query.username = new RegExp(username, 'i'); // 'i' 代表忽略大小写
    if (uid) query.uid = uid
    if (phoneNum) query.phoneNum = new RegExp(phoneNum, 'i');
    if (email) query.email = new RegExp(email, 'i');
    if (subType) query.subType = subType;
    if (bqMoney) query.bqMoney = bqMoney;
    if (subNum) query.subNum = subNum;
    if (startDate) {
        // 数据库中记录的结束时间要在 startDate 之后
        query.endDate = { $gte: new Date(startDate) };
    }
    if (endDate) {
        // 数据库中记录的结束时间要在 endDate 之前
        query.endDate = { ...query.endDate, $lte: new Date(endDate) };
    }
    try{
        const results = await subModel.aggregate([
            { $match: query },
            { $addFields: {
                    subStatus: {
                        // 检查endDate是否小于当前时间
                        $cond: { if: { $lt: [ "$endDate", new Date() ] }, then: 1, else: 0 }
                    }
                }},
            { $facet: {
                    "totalData": [{ $skip: skipValue }, { $limit: pageSize }],
                    "totalCount": [{ $count: "count" }]
                }}
        ]);
        // 从聚合结果中提取数据和计数
        const data = results[0].totalData;
        const total = results[0].totalCount[0] ? results[0].totalCount[0].count : 0;
        let uids = data.map(item=>item.uid)
        //统计订阅次数
        const subCounts = await subModel.aggregate([
            { $match: { uid: { $in: uids } } },
            { $group: { _id: "$uid", subNum: { $sum: 1 } } }
        ]);
        // 将订单次数转换成一个方便查询的对象Map
        const subCountsMap = subCounts.reduce((map, item) => {
            map[item._id] = item.subNum;
            return map;
        }, {});

        //关联用户信息
        const user = await subUserModel.find({ uid: { $in: uids }}).lean();
        const usersMap = user.reduce((map, user) => {
            map[user.uid] = user;
            return map;
        }, {});
        const dataWithUserInfo = data.map(item => {
            const userInfo = usersMap[item.uid] || null;
            const subCount = subCountsMap[item.uid] || 0;
            return {
                ...item,
                ...userInfo ,// 如果找不到用户则附加null
                subNum:subCount,
            };
        });
        // 发送响应
        res.status(200).send({
            code: 0,
            data:dataWithUserInfo,
            total: total,
            currentPage:page,
            pageSize:pageSize,
            message: '查询成功'
        });
    }catch (e) {
        next(e);
    }
})

router.post('/addSub',function(req,res,next){
    let {uid,subType,bqMoney,startDate,endDate,subscripte_type,subRAM,} = req.body
    subModel.create({
        uid,
        subType,
        bqMoney,
        subscripte_type,
        subRAM,
        startDate:new Date(startDate),
        endDate:new Date(endDate),
        subId:uuidv4().split('-').join(""),
    }).then((data)=>{
        res.status(200).send({
            code:0,
            message:'添加成功'
        });
    }).catch((err)=>{
        if (err.name === 'ValidationError') {
            // 打印出错误的字段
            console.error('Validation error:', err.errors);
            // 返回自定义的错误信息
            res.status(400).json({ message: 'Validation error', errors: err.errors });
        } else {
            next(err);
        }
    })
})

router.post('/editSub',function(req,res,next){
    let {subId,uid,subType,bqMoney,startDate,endDate,subscripte_type,subRAM,} = req.body
    subModel.updateOne(
        { "subId": subId }, // 查询条件
        { $set: { uid,subType,bqMoney,startDate,endDate,subscripte_type,subRAM, }} // 更新操作
    ).then((data)=>{
        res.status(200).send({
            code:0,
            message:'修改成功'
        });
    }).catch(err=>{
        next(err);
    })
})

router.post('/delSub',async function(req,res,next){
    let {subId} = req.body
    try{
        const data = await subModel.find({ subId: subId}).lean();
        if(data.length>0){
            subModel.deleteOne(
                { "subId": subId },
            ).then((data)=>{
                res.status(200).send({
                    code:0,
                    message:'删除成功'
                });
            }).catch(err=>{
                next(err);
            })
        }
    }catch(err){
        next(err)
    }
})

//当前用户订阅次数
router.post('/subDetailByUid',async function(req,res,next){
    let {uid} = req.body
    try{
        let data = await subModel.find({uid:uid}).lean()
        const now = new Date(); // 当前时间
        const updatedData = data.map((item) => {
            // 判断是否过期
            const isExpired = item.endDate < now;
            // 添加subStatus字段
            return {
                ...item, // 既有订单详情
                subStatus: isExpired ? 1 : 0
            };
        });
        res.status(200).send({
            data:updatedData,
            code:0,
            message:'查询成功'
        });
    }catch(err){
        next(err)
    }
})


module.exports = router;
